package com.rz.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rz.admin.entity.SysDictData;
import com.rz.admin.mapper.SysDictDataMapper;
import com.rz.admin.service.ISysDictDataService;
import com.rz.core.config.RedisKeys;
import com.rz.core.exception.GlobalException;
import com.rz.core.kit.RedisKit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Rui.Zhou
 * @since 2018-07-12
 */
@Service
public class SysDictDataServiceImpl extends ServiceImpl<SysDictDataMapper, SysDictData> implements ISysDictDataService {

    @Autowired
    private SysDictDataMapper sysDictDataMapper;
    @Resource
    private RedisKit redisKit;

    public List<SysDictData> getByDictValue(String dictValue) {
        return sysDictDataMapper.getByDictValue(dictValue);
    }

    public IPage<SysDictData> getPage(SysDictData sysDictData) {
        QueryWrapper<SysDictData> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dict_value",sysDictData.getDictValue());
        Page<SysDictData> page = new Page<>(sysDictData.getPageNo(),sysDictData.getPageSize());
        return page(page,queryWrapper);
    }

    public boolean saveDictData(SysDictData sysDictData) {
        if(sysDictData.getId()==null){
            QueryWrapper<SysDictData> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("dict_value",sysDictData.getDictValue());
            queryWrapper.eq("dictdata_value",sysDictData.getDictdataValue());
            SysDictData dictData = getOne(queryWrapper);
            if(dictData!=null){
                throw new GlobalException("编码已存在");
            }
        }
        boolean saveOk = saveOrUpdate(sysDictData);
        if(saveOk){
            redisKit.putHash(RedisKeys.DICT_KEY,sysDictData.getDictValue()+"_"+sysDictData.getDictdataValue(),sysDictData);
        }
        return saveOk;
    }
}
